// pages/date/add.js
const app = getApp()

Page({
  data: {
    formData: {
      name: '',
      dateType: 'anniversary',
      baseDate: null,
      baseDateText: '',
      isYearly: true,
      notes: ''
    },
    showDatePicker: false,
    isSubmitting: false,
    currentDate: new Date().getTime(),
    minDate: new Date(2000, 0, 1).getTime(),
    maxDate: new Date(2100, 11, 31).getTime()
  },

  onLoad() {
    console.log('页面加载，初始化数据')
    console.log('初始formData:', this.data.formData)
    
    // 初始化当前日期
    this.setCurrentDateText()
    
    // 确保Switch组件的初始状态正确
    console.log('初始isYearly值:', this.data.formData.isYearly)
    console.log('Switch应该显示为:', this.data.formData.isYearly ? '开启' : '关闭')
  },

  // 设置当前日期文本
  setCurrentDateText() {
    const date = this.data.formData.baseDate || new Date()
    const text = this.formatDate(date)
    console.log('设置当前日期文本:', text)
    this.setData({
      'formData.baseDateText': text
    })
  },

  // 格式化日期
  formatDate(date) {
    // 处理Date对象或时间戳
    const dateObj = typeof date === 'number' ? new Date(date) : date
    const year = dateObj.getFullYear()
    const month = dateObj.getMonth() + 1
    const day = dateObj.getDate()
    return `${year}年${month.toString().padStart(2, '0')}月${day.toString().padStart(2, '0')}日`
  },

  // 字段变化处理
  onFieldChange(event) {
    const { field } = event.currentTarget.dataset
    const value = event.detail
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 日期类型变化
  onDateTypeChange(event) {
    this.setData({
      'formData.dateType': event.detail
    })
  },

  // 选择日期类型（点击事件）
  selectDateType(event) {
    const { type } = event.currentTarget.dataset
    this.setData({
      'formData.dateType': type
    })
  },

  // 每年重复开关变化 - 微信原生switch事件处理
  onYearlyChange(event) {
    console.log('Switch event received:', event);
    console.log('Event detail value:', event.detail.value);
    
    // 微信原生switch返回的是event.detail.value
    const isChecked = event.detail.value;
    console.log('Setting isYearly to:', isChecked);
    
    this.setData({
      'formData.isYearly': isChecked
    }, () => {
      console.log('After setData - isYearly:', this.data.formData.isYearly);
    });
  },

  // 显示日期选择器（使用Vant DatetimePicker）
  showDatePicker() {
    this.setData({
      showDatePicker: true,
      currentDate: this.data.formData.baseDate || new Date().getTime()
    });
  },

  // 日期确认选择
  onDateConfirm(event) {
    const date = new Date(event.detail);
    const text = this.formatDate(date);
    
    this.setData({
      'formData.baseDate': date.getTime(),
      'formData.baseDateText': text,
      showDatePicker: false
    });
  },

  // 日期选择取消
  onDateCancel() {
    this.setData({
      showDatePicker: false
    });
  },



  // 表单提交
  onSubmit(event) {
    const formData = event.detail.value
    const errors = this.validateForm(formData)
    
    if (errors.length > 0) {
      wx.showToast({
        title: errors[0],
        icon: 'none',
        duration: 2000
      })
      return
    }

    this.submitForm()
  },

  // 表单验证
  validateForm(formData) {
    const errors = []

    if (!formData.name || formData.name.trim().length === 0) {
      errors.push('请输入日期名称')
    } else if (formData.name.trim().length > 20) {
      errors.push('日期名称不能超过20个字')
    }

    if (!this.data.formData.baseDate) {
      errors.push('请选择日期')
    }

    if (formData.notes && formData.notes.length > 100) {
      errors.push('备注信息不能超过100个字')
    }

    return errors
  },

  // 提交表单
  async submitForm() {
    this.setData({ isSubmitting: true })

    try {
      // 模拟提交延迟
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      // 这里应该是实际的API调用
      // const result = await wx.request({
      //   url: '/api/dates',
      //   method: 'POST',
      //   data: this.prepareSubmitData()
      // })

      // 模拟成功响应
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      })

    } catch (error) {
      wx.showToast({
        title: '添加失败，请重试',
        icon: 'error',
        duration: 2000
      })
    } finally {
      this.setData({ isSubmitting: false })
    }
  },

  // 准备提交数据
  prepareSubmitData() {
    const { formData } = this.data
    return {
      name: formData.name.trim(),
      dateType: formData.dateType,
      baseDate: new Date(formData.baseDate).toISOString(), // 时间戳转Date对象再转ISO字符串
      isYearly: formData.isYearly,
      notes: formData.notes ? formData.notes.trim() : '',
      coupleId: app.globalData.userInfo?.coupleId
    }
  },

  // 返回上一页
  onBack() {
    wx.navigateBack()
  }
})